@echo off
setlocal EnableDelayedExpansion

echo ===========================================
echo       APIViewer Backend Startup Script
echo ===========================================

REM Set default values
set DEFAULT_HOST=0.0.0.0
set DEFAULT_PORT=8000
set SCRIPT_DIR=%~dp0
set BACKEND_DIR=%SCRIPT_DIR%backend

REM Get command line parameters
set HOST=%DEFAULT_HOST%
set PORT=%DEFAULT_PORT%
set CLEANUP_MODE=false
set REINSTALL_MODE=false
set MIGRATE_MODE=false
set PRODUCTION_MODE=false
set CREATE_VENV_MODE=false

REM Check if in correct directory
if not exist "%BACKEND_DIR%" (
    echo Error: backend directory not found
    echo Please run this script from project root directory
    pause
    exit /b 1
)

REM Parse command line arguments
:parse_args
if "%~1"=="" goto validate_args
if "%~1"=="--host" (
    set HOST=%~2
    shift
    shift
    goto parse_args
)
if "%~1"=="--port" (
    set PORT=%~2
    shift
    shift
    goto parse_args
)
if "%~1"=="-h" (
    set HOST=%~2
    shift
    shift
    goto parse_args
)
if "%~1"=="-p" (
    set PORT=%~2
    shift
    shift
    goto parse_args
)
if "%~1"=="--cleanup" (
    set CLEANUP_MODE=true
    shift
    goto parse_args
)
if "%~1"=="--reinstall" (
    set REINSTALL_MODE=true
    shift
    goto parse_args
)
if "%~1"=="--migrate" (
    set MIGRATE_MODE=true
    shift
    goto parse_args
)
if "%~1"=="--production" (
    set PRODUCTION_MODE=true
    shift
    goto parse_args
)
if "%~1"=="--create-venv" (
    set CREATE_VENV_MODE=true
    shift
    goto parse_args
)
if "%~1"=="--help" (
    call :show_help
    exit /b 0
)
REM If only numbers, assume port
echo %~1 | findstr /R "^[0-9][0-9]*$" >nul
if %errorlevel% equ 0 (
    set PORT=%~1
    shift
    goto parse_args
)
REM If contains dot, assume host address
echo %~1 | findstr /R "\." >nul
if %errorlevel% equ 0 (
    set HOST=%~1
    shift
    goto parse_args
)
shift
goto parse_args

:validate_args
REM Validate port number
set /a PORT_TEST=!PORT! 2>nul
if !PORT_TEST! equ 0 if not "!PORT!"=="0" (
    echo Error: Port must be numeric, current value: !PORT!
    pause
    exit /b 1
)

if !PORT! lss 1 (
    echo Error: Port must be greater than 0
    pause
    exit /b 1
)

if !PORT! gtr 65535 (
    echo Error: Port cannot exceed 65535
    pause
    exit /b 1
)

REM Switch to backend directory
cd /d "%BACKEND_DIR%"
if %errorlevel% neq 0 (
    echo Error: Cannot switch to backend directory
    pause
    exit /b 1
)

REM Check if main.py exists
if not exist "main.py" (
    echo Error: main.py file not found
    echo Please ensure you are in the correct project directory
    pause
    exit /b 1
)

echo Startup Configuration:
echo    Directory: !CD!
echo    Host: !HOST!
echo    Port: !PORT!
if "!PRODUCTION_MODE!"=="true" (
    echo    Mode: Production
) else (
    echo    Mode: Development
)
echo    Service API: http://!HOST!:!PORT!
echo    API Documentation: http://!HOST!:!PORT!/docs
echo ==========================================

REM Check if port is in use
netstat -an | findstr ":!PORT! " >nul
if !errorlevel! equ 0 (
    echo Warning: Port !PORT! may be in use
    echo If startup fails, try using a different port
    echo.
)

REM Check if Python is installed
python --version >nul 2>&1
if !errorlevel! neq 0 (
    echo Error: Python not found
    echo Please install Python first: https://www.python.org/
    pause
    exit /b 1
)

echo Python version: 
python --version

REM Create virtual environment mode
if "!CREATE_VENV_MODE!"=="true" (
    echo Creating virtual environment...
    if exist "venv" rmdir /s /q "venv"
    python -m venv venv
    if !errorlevel! neq 0 (
        echo Virtual environment creation failed
        pause
        exit /b 1
    )
    echo Virtual environment created successfully
    echo.
)

REM Check if virtual environment exists
set VENV_ACTIVATED=false
if exist "venv\Scripts\activate.bat" (
    echo Activating virtual environment...
    call venv\Scripts\activate.bat
    set VENV_ACTIVATED=true
) else if exist ".venv\Scripts\activate.bat" (
    echo Activating virtual environment...
    call .venv\Scripts\activate.bat
    set VENV_ACTIVATED=true
) else (
    echo No virtual environment found, using system Python
    echo Suggest creating virtual environment: %~nx0 --create-venv
    echo.
)

REM Cleanup mode
if "!CLEANUP_MODE!"=="true" (
    echo Cleaning Python cache...
    for /d /r . %%d in (__pycache__) do @if exist "%%d" rmdir /s /q "%%d"
    for /r . %%f in (*.pyc) do @if exist "%%f" del /q "%%f"
    for /r . %%f in (*.pyo) do @if exist "%%f" del /q "%%f"
    echo Cleanup completed
    echo.
)

REM Reinstall mode
if "!REINSTALL_MODE!"=="true" (
    echo Reinstalling dependencies...
    pip uninstall -y -r requirements.txt >nul 2>&1
)

REM Check if dependencies are installed
pip show fastapi >nul 2>&1
if !errorlevel! neq 0 (
    echo FastAPI not found, installing dependencies...
    pip install -r requirements.txt
    if !errorlevel! neq 0 (
        echo Dependency installation failed
        echo Please check network connection and pip configuration
        pause
        exit /b 1
    )
    echo Dependencies installed successfully
    echo.
)

REM Database migration mode
if "!MIGRATE_MODE!"=="true" (
    echo Executing database migration...
    if exist "alembic.ini" (
        alembic upgrade head
        if !errorlevel! neq 0 (
            echo Database migration failed
            pause
            exit /b 1
        )
        echo Database migration completed
    ) else if exist "migrate_database.py" (
        python migrate_database.py
        if !errorlevel! neq 0 (
            echo Database migration failed
            pause
            exit /b 1
        )
        echo Database migration completed
    ) else (
        echo No database migration files found
    )
    echo.
)

echo Starting API server...
echo Press Ctrl+C to stop the server
echo.

REM Set environment variables
if "!PRODUCTION_MODE!"=="true" (
    set "ENVIRONMENT=production"
    set "DEBUG=false"
) else (
    set "ENVIRONMENT=development"
    set "DEBUG=true"
)

REM Start FastAPI server
if "!PRODUCTION_MODE!"=="true" (
    python -m uvicorn main:app --host !HOST! --port !PORT!
) else (
    python -m uvicorn main:app --host !HOST! --port !PORT! --reload
)

if !errorlevel! neq 0 (
    echo.
    echo Backend server startup failed
    echo Possible solutions:
    echo    1. Check if port !PORT! is in use
    echo    2. Try using a different port: %~nx0 --port 8001
    echo    3. Clean project: %~nx0 --cleanup
    echo    4. Reinstall dependencies: %~nx0 --reinstall
    echo    5. Execute database migration: %~nx0 --migrate
    echo    6. Create virtual environment: %~nx0 --create-venv
    pause
    exit /b 1
)

echo.
echo Backend server has been closed
pause
exit /b

:show_help
echo Usage: start-backend.bat [options]
echo.
echo Options:
echo   --host, -h HOST          Set server address (default: 0.0.0.0)
echo   --port, -p PORT          Set port number (default: 8000)
echo   --cleanup                Clean Python cache files
echo   --reinstall              Reinstall dependencies
echo   --migrate                Execute database migration
echo   --production             Production mode startup
echo   --create-venv            Create virtual environment
echo   --help                   Show this help information
echo.
echo Examples:
echo   start-backend.bat
echo   start-backend.bat --host 127.0.0.1
echo   start-backend.bat --port 9000
echo   start-backend.bat --cleanup
echo   start-backend.bat --migrate
echo   start-backend.bat --production
echo   start-backend.bat --create-venv
echo   start-backend.bat 8080
echo   start-backend.bat 192.168.1.100
goto :eof 